﻿using YKXiangQi.Enums;
using YKXiangQi.Models;
using YKXiangQi.Common;

namespace YKXiangQi.Utilities
{
    public class FenReader
    {
        public static FenInfo Read(string fen)
        {
            var result = new FenInfo();

            fen = fen.Replace("  ", " "); //replace any double space with single space
            string[] fenData = fen.Split(new char[] { ' ' });

            if (fenData.Length > 1)
            {
                if (fenData[1][0] == 'w' || fenData[1][0] == 'W')
                    result.ActiveColor = Sides.Red;
                else
                    result.ActiveColor = Sides.Black;
            }

            if (fenData.Length > 3)
                result.FullMoveNumber = fenData[1][4].ToInt32();

            string[] fenRowData = fenData[0].Split(new char[] { '/' });

            for (int row = 0; row < fenRowData.Length; row++)
            {
                int column = 0;
                for (int i = 0; i < fenRowData[row].Length; i++)
                {
                    int x = fenRowData[row][i].ToString().ToInt32();
                    if (x == 0)
                    {
                        result.Pieces[row, column] = Piece.FromString(fenRowData[row][i].ToString());
                        column++;
                    }
                    else
                    {
                        column += x;
                    }
                }
            }

            return result;
        }
    }
}
